<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
global $api_functions;
$api_functions = array();

// convert UTF-8 because not supported by XMLRPC
function wpa_convert($data){
    if(is_array($data)){
	foreach($data as $k=>$v){
	    $data[$k] = wpa_convert($v); 
	}
	return $data;
    }else{
	return utf8_encode($data);
    }
    
}
function wpa_result($result){
    
    return array('error'=>'', 'result'=>wpa_convert($result));
}
function wpa_error($error){
    return array('error'=>$error, 'result'=>'');
}


function wpa_verify_key($args){
    global $protect_wp,$config;
    if(is_array($args)) $key = $args[0];
    else $key = $args;
    $wp_config = $protect_wp->config;
    if(md5($wp_config['key'].$config['root_url']) != $key) return wpa_error('Verification filed!');
}
// wpa_ping($key, $text)
// return $text if verification successfull
function wpa_ping($args){
    $error = wpa_verify_key($args);
    return ($error ? $error : wpa_result($args[1]));
}
$api_functions['ping'] = 'wpa_ping';

function wpa_get_products_list($args){
    global $db;
    wpa_verify_key($args);
    $products = array();
    foreach((array)$db->get_products_list() as $p){
        $products[$p['product_id']] = array('product_id' =>$p['product_id'], 'title'=>$p['title']);
    }
    return wpa_result($products);
}
$api_functions['get_products_list'] = 'wpa_get_products_list';

function wpa_get_member_id($args){
    global $db;
    wpa_verify_key($args);
    if($db->check_login($args[1],$args[2],&$member_id)) return wpa_result($member_id);
    return wpa_result(0);
    
}
$api_functions['get_member_id'] = 'wpa_get_member_id';

function wpa_get_user($args){
    global $db;
    wpa_verify_key($args);
    $user_id = intval($args[1]);
    
    $user = $db->get_user($user_id);
    if(!$user) return;
    // Now build user's subscriptions in a way required by plugin.
    $subscriptions = array();
    $now = date('Y-m-d');
    $now_tm = strtotime($now);
    foreach((array)$db->get_user_payments($user_id,1) as $p){
        $is_active = ($p['begin_date']<=$now && $p['expire_date']>=$now);
        if($is_active)
            $subscriptions[$p['product_id']]['active'] = 1;
        else
            $subscriptions[$p['product_id']]['expired'] = 1;

        // Calculate subscription length in days ;
        $beg_tm = strtotime($p['begin_date']);
        $end_tm = strtotime($p['expire_date']);
        $diff = ($end_tm>=$now_tm? $now_tm : $end_tm) - ($beg_tm >=$now_tm ? $now_tm : $beg_tm);
        $diff_d = intval($diff/(24 * 3600));
        $subscriptions[$p['product_id']]['days'] +=  $diff_d;
    }
    $user['subscriptions'] = $subscriptions;
    return wpa_result($user);
}
$api_functions['get_user'] =  "wpa_get_user";

?>
